DonationModal.tsx 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365
  1. 'use client';
  2. import { useState, useEffect, useRef, useCallback } from 'react';
  3. import { fetchApi } from '@/lib/utils/client';
  4. import useAuth from '@/hooks/useAuth';
  5. import { DropdownData } from '@/types/response/mypage/dropdown';
  6. import './donation-modal.scss';
  7. type CrewMemberInfo = {
  8. crewMemberID: number;
  9. nickname: string;
  10. thumb: string|null;
  11. channelName: string|null;
  12. };
  13. type ActiveCrew = {
  14. crewSessionID: number;
  15. title: string;
  16. crewName: string;
  17. members: CrewMemberInfo[];
  18. }|null;
  19. type SignatureItem = {
  20. id: number;
  21. title: string;
  22. amount: number;
  23. matchType: number;
  24. imageUrl: string;
  25. };
  26. type SignatureListResponse = {
  27. list: SignatureItem[];
  28. total: number;
  29. hasMore: boolean;
  30. };
  31. type Props = {
  32. channelSID: string;
  33. onClose: () => void;
  34. };
  35. const PER_PAGE = 6;
  36. export default function DonationModal({ channelSID, onClose }: Props)
  37. {
  38. const { member } = useAuth();
  39. const [amount, setAmount] = useState(1000);
  40. const [message, setMessage] = useState('');
  41. const [sendName, setSendName] = useState(member?.name || member?.sid || '');
  42. const [isAnonymous, setIsAnonymous] = useState(false);
  43. const [pointBalance, setPointBalance] = useState<number|null>(null);
  44. const [activeCrew, setActiveCrew] = useState<ActiveCrew>(null);
  45. const [selectedMember, setSelectedMember] = useState<number|null>(null);
  46. const [sending, setSending] = useState(false);
  47. const [done, setDone] = useState(false);
  48. // 시그니처 이미지 페이징
  49. const [signatures, setSignatures] = useState<SignatureItem[]>([]);
  50. const [sigPage, setSigPage] = useState(1);
  51. const [sigHasMore, setSigHasMore] = useState(true);
  52. const [sigLoading, setSigLoading] = useState(false);
  53. const [selectedSigId, setSelectedSigId] = useState<number|null>(null);
  54. const sigSentinelRef = useRef<HTMLDivElement|null>(null);
  55. const presetAmounts = [1000, 3000, 5000, 10000, 30000, 50000];
  56. useEffect(() => {
  57. fetchApi<ActiveCrew>(`/api/donation/crew/active/${channelSID}`)
  58. .then(res => {
  59. if (res.data) {
  60. setActiveCrew(res.data);
  61. }
  62. })
  63. .catch(() => {});
  64. }, [channelSID]);
  65. useEffect(() => {
  66. fetchApi<DropdownData>('/api/mypage/dropdown', { silent: true })
  67. .then(res => {
  68. if (res.data) {
  69. setPointBalance(res.data.spendableBalance);
  70. }
  71. })
  72. .catch(() => {});
  73. }, []);
  74. // 시그니처 이미지 초기 로드 및 페이징
  75. const loadSignatures = useCallback(async (page: number) => {
  76. if (sigLoading) {
  77. return;
  78. }
  79. setSigLoading(true);
  80. try {
  81. const res = await fetchApi<SignatureListResponse>(
  82. `/api/donation/signatures/${channelSID}?page=${page}&perPage=${PER_PAGE}`,
  83. { silent: true }
  84. );
  85. if (res.data) {
  86. setSignatures(prev => page === 1 ? res.data!.list : [...prev, ...res.data!.list]);
  87. setSigHasMore(res.data.hasMore);
  88. }
  89. } catch {
  90. setSigHasMore(false);
  91. } finally {
  92. setSigLoading(false);
  93. }
  94. }, [channelSID, sigLoading]);
  95. useEffect(() => {
  96. loadSignatures(1);
  97. // eslint-disable-next-line react-hooks/exhaustive-deps
  98. }, [channelSID]);
  99. // IntersectionObserver 무한 스크롤
  100. useEffect(() => {
  101. const sentinel = sigSentinelRef.current;
  102. if (!sentinel || !sigHasMore || sigLoading) {
  103. return;
  104. }
  105. const observer = new IntersectionObserver((entries) => {
  106. if (entries[0].isIntersecting) {
  107. const next = sigPage + 1;
  108. setSigPage(next);
  109. loadSignatures(next);
  110. }
  111. }, { threshold: 0.5 });
  112. observer.observe(sentinel);
  113. return () => observer.disconnect();
  114. }, [sigPage, sigHasMore, sigLoading, loadSignatures]);
  115. const handleSignatureClick = (sig: SignatureItem) => {
  116. setSelectedSigId(sig.id);
  117. setAmount(sig.amount);
  118. };
  119. const handleSend = async () => {
  120. if (amount < 1000) {
  121. alert('최소 후원 금액은 1,000원입니다.');
  122. return;
  123. }
  124. const finalSendName = isAnonymous ? '익명' : sendName.trim();
  125. if (!finalSendName) {
  126. alert('보내는 사람 이름을 입력해 주세요.');
  127. return;
  128. }
  129. setSending(true);
  130. try {
  131. const body: Record<string, unknown> = {
  132. channelSID,
  133. amount,
  134. message: message || null,
  135. sendName: finalSendName
  136. };
  137. if (activeCrew && selectedMember) {
  138. body.crewSessionID = activeCrew.crewSessionID;
  139. body.crewMemberID = selectedMember;
  140. }
  141. const res = await fetchApi('/api/donation/send', {
  142. method: 'POST',
  143. body,
  144. silent: true
  145. });
  146. if (!res.success) {
  147. const msg = res.message ?? '';
  148. if (/\uC794\uC561/.test(msg) || msg.includes('부족')) {
  149. alert('POINT가 부족합니다.');
  150. } else {
  151. alert(msg || '후원에 실패했습니다.');
  152. }
  153. return;
  154. }
  155. setDone(true);
  156. } catch (err: unknown) {
  157. alert(err instanceof Error ? err.message : '후원에 실패했습니다.');
  158. } finally {
  159. setSending(false);
  160. }
  161. };
  162. if (done) {
  163. return (
  164. <div className="donation-modal" role="dialog" aria-modal="true" aria-labelledby="donation-modal-title">
  165. <div className="donation-modal__overlay" onClick={onClose} />
  166. <div className="donation-modal__box">
  167. <div className="donation-modal__done">
  168. <div className="donation-modal__done-icon" aria-hidden="true">🎉</div>
  169. <p className="donation-modal__done-text">{amount.toLocaleString()}원 후원 완료!</p>
  170. <button type="button" className="donation-modal__btn donation-modal__btn--primary" onClick={onClose}>닫기</button>
  171. </div>
  172. </div>
  173. </div>
  174. );
  175. }
  176. return (
  177. <div className="donation-modal" role="dialog" aria-modal="true" aria-labelledby="donation-modal-title">
  178. <div className="donation-modal__overlay" onClick={onClose} />
  179. <div className="donation-modal__box">
  180. <div className="donation-modal__header">
  181. <h2 id="donation-modal-title" className="donation-modal__title">후원하기</h2>
  182. <button type="button" className="donation-modal__close" onClick={onClose} aria-label="닫기">&times;</button>
  183. </div>
  184. <div className="donation-modal__body">
  185. {/* 시그니처 이미지 그리드 (상단, 이미지 있는 것만) */}
  186. {signatures.length > 0 && (
  187. <div className="donation-modal__signatures">
  188. <label className="donation-modal__label">시그니처 선택 (선택 시 금액 자동 입력)</label>
  189. <div className="donation-modal__signature-grid" role="listbox" aria-label="시그니처 이미지">
  190. {signatures.map(sig => {
  191. const isActive = selectedSigId === sig.id;
  192. return (
  193. <button
  194. type="button"
  195. key={sig.id}
  196. className={`donation-modal__signature${isActive ? ' donation-modal__signature--active' : ''}`}
  197. onClick={() => handleSignatureClick(sig)}
  198. aria-selected={isActive}
  199. role="option"
  200. >
  201. <img src={sig.imageUrl} alt={sig.title} className="donation-modal__signature-img" />
  202. <span className="donation-modal__signature-amount">{sig.amount.toLocaleString()}원</span>
  203. </button>
  204. );
  205. })}
  206. {sigHasMore && <div ref={sigSentinelRef} className="donation-modal__signature-sentinel" aria-hidden="true" />}
  207. {sigLoading && <div className="donation-modal__signature-loading">불러오는 중...</div>}
  208. </div>
  209. </div>
  210. )}
  211. {/* 크루원 선택 (시그니처 바로 아래) */}
  212. {activeCrew && activeCrew.members.length > 0 && (
  213. <div className="donation-modal__crew">
  214. <label className="donation-modal__crew-label">
  215. 크루원에게 후원 <span className="donation-modal__crew-tag">{activeCrew.crewName}</span>
  216. </label>
  217. <div className="donation-modal__crew-list">
  218. <button
  219. type="button"
  220. className={`donation-modal__crew-item${selectedMember === null ? ' donation-modal__crew-item--active' : ''}`}
  221. onClick={() => setSelectedMember(null)}
  222. >
  223. <div className="donation-modal__crew-thumb donation-modal__crew-thumb--default">채널</div>
  224. <span>채널 주인</span>
  225. </button>
  226. {activeCrew.members.map(m => (
  227. <button
  228. type="button"
  229. key={m.crewMemberID}
  230. className={`donation-modal__crew-item${selectedMember === m.crewMemberID ? ' donation-modal__crew-item--active' : ''}`}
  231. onClick={() => setSelectedMember(m.crewMemberID)}
  232. >
  233. {m.thumb ? (
  234. <img src={m.thumb} alt="" className="donation-modal__crew-thumb" />
  235. ) : (
  236. <div className="donation-modal__crew-thumb donation-modal__crew-thumb--default">{m.nickname.charAt(0)}</div>
  237. )}
  238. <span>{m.nickname}</span>
  239. </button>
  240. ))}
  241. </div>
  242. </div>
  243. )}
  244. {/* 별명 */}
  245. <div className="donation-modal__field">
  246. <div className="donation-modal__label-row">
  247. <label htmlFor="donation-sendname">별명</label>
  248. <label className="donation-modal__anon-toggle">
  249. <input
  250. type="checkbox"
  251. checked={isAnonymous}
  252. onChange={e => setIsAnonymous(e.target.checked)}
  253. />
  254. <span>익명</span>
  255. </label>
  256. </div>
  257. <input
  258. id="donation-sendname"
  259. type="text"
  260. value={isAnonymous ? '익명' : sendName}
  261. onChange={e => setSendName(e.target.value)}
  262. placeholder="보내는 사람"
  263. maxLength={20}
  264. disabled={isAnonymous}
  265. />
  266. </div>
  267. {/* 금액 */}
  268. <div className="donation-modal__field">
  269. <div className="donation-modal__label-row">
  270. <label htmlFor="donation-amount">후원 금액</label>
  271. {pointBalance !== null && (
  272. <span className="donation-modal__balance" aria-live="polite">
  273. 잔액 {pointBalance.toLocaleString()}P
  274. </span>
  275. )}
  276. </div>
  277. <input
  278. id="donation-amount"
  279. type="number"
  280. min={1000}
  281. max={10000000}
  282. step={1000}
  283. value={amount}
  284. onChange={e => { setAmount(Number(e.target.value)); setSelectedSigId(null); }}
  285. />
  286. <div className="donation-modal__presets" role="group" aria-label="금액 프리셋">
  287. {presetAmounts.map(a => (
  288. <button
  289. type="button"
  290. key={a}
  291. className={`donation-modal__preset${amount === a ? ' donation-modal__preset--active' : ''}`}
  292. onClick={() => { setAmount(a); setSelectedSigId(null); }}
  293. >
  294. {a.toLocaleString()}원
  295. </button>
  296. ))}
  297. </div>
  298. </div>
  299. {/* 메시지 */}
  300. <div className="donation-modal__field">
  301. <div className="donation-modal__label-row">
  302. <label htmlFor="donation-message">메시지 (선택)</label>
  303. <span className={`donation-modal__msg-counter${message.length >= 100 ? ' donation-modal__msg-counter--max' : ''}`} aria-live="polite">
  304. {message.length}/100
  305. </span>
  306. </div>
  307. <textarea
  308. id="donation-message"
  309. value={message}
  310. onChange={e => setMessage(e.target.value)}
  311. placeholder="응원 메시지를 남겨주세요"
  312. maxLength={100}
  313. rows={2}
  314. />
  315. </div>
  316. </div>
  317. {/* 푸터: 취소 / 보내기 */}
  318. <div className="donation-modal__footer">
  319. <button type="button" className="donation-modal__btn" onClick={onClose}>취소</button>
  320. <button
  321. type="button"
  322. className="donation-modal__btn donation-modal__btn--primary"
  323. onClick={handleSend}
  324. disabled={sending}
  325. >
  326. {sending ? '전송 중...' : '보내기'}
  327. </button>
  328. </div>
  329. </div>
  330. </div>
  331. );
  332. }